package org.jetnuke.modules.download;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.dao.DownloadDownloadDAO;
import org.jetnuke.dao.DownloadVoteDataDAO;
import org.jetnuke.entities.DownloadsVoteData;

public class Comments implements IAction {

	int id;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jetnuke.common.IAction#exec(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse,
	 *      org.apache.velocity.VelocityContext, org.jetnuke.common.IModuleInfo,
	 *      java.lang.String, org.jetnuke.common.IUserInfo,
	 *      org.jetnuke.common.IAdminInfo)
	 */
	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		DownloadDownloadDAO ddm=DataAccessDriver.getInst().newDownloadDownloadDAO();
		vc.put("down", ddm.retrieveByPK(id));
		HashMap totalVotesMap = new HashMap();
		HashMap averageVotesMap = new HashMap();
		DownloadVoteDataDAO dvdm=DataAccessDriver.getInst().newDownloadVoteDAO();
		List ls =dvdm.selectWithComment(id);// downloads_votedataPeer.doSelect(new Criteria().add(
				//downloads_votedataPeer.RATINGCOMMENTS, (Object) "",
				//Criteria.NOT_EQUAL).addDescendingOrderByColumn(
				//downloads_votedataPeer.RATINGTIMESTAMP));
		vc.put("comments", ls);
		Iterator it = ls.iterator();
		while (it.hasNext()) {
			DownloadsVoteData vote = (DownloadsVoteData) it.next();
			String user = vote.getRATINGUSER();
			if (user != null && user.length() > 0) {
				Iterator it2 = dvdm.getByRatingUser(user).iterator();//downloads_votedataPeer.doSelect(
						//new Criteria().add(downloads_votedataPeer.RATINGUSER,
							//	user)).iterator();
				int sum = 0;
				int count = 0;
				while (it2.hasNext()) {
					DownloadsVoteData user_vote = (DownloadsVoteData) it2
							.next();
					count++;
					sum += user_vote.getRATING();
				}
				if (count > 0) {
					totalVotesMap.put(vote, new Integer(count));
					averageVotesMap.put(vote,
							new Double(sum / ((double) count)));
				}
			}
		}
		vc.put("totalVotesMap", totalVotesMap);
		vc.put("averageVotesMap", averageVotesMap);
		return new ActionForward(op, info);
	}

	public void setId(int id) {
		this.id = id;
	}
}
